package com.eascs.ant.user.service;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eascs.ant.common.service.BaseSevice;
import com.eascs.ant.user.entity.Team;
import com.eascs.ant.user.entity.TeamUpdate;
import com.eascs.common.assertion.util.AssertInfoUtils;

@Service
public class TeamService extends BaseSevice {
	@Inject
	private TeamItemService teamItemService;

	public List<Team> getAllTeam() {
		return this.proxyDao.findEntitys("select * from team", Team.class);
	}

	public Team getTeamById(String id) {
		return this.proxyDao.getById(Team.class, id);
	}

	public Team getTeamByCode(String code) {
		Team team = new Team();
		team.setCode(code);
		return this.proxyDao.findEntityWithAny(team);
	}

	@Transactional(transactionManager = "ticketTransactionManager")
	public void insertTeam(Team team) {
		initTeamItemWithLeader(team.getCode(), team.getLeaderUserCode());
		this.proxyDao.insert(team);
	}

	private void initTeamItemWithLeader(String teamCode, String leaderUserCode) {
		Team team = new Team();
		team.setLeaderUserCode(leaderUserCode);
		List<Team> teams = this.proxyDao.findEntitysWithAny(team);
		AssertInfoUtils.assertTrue(teams.isEmpty() || (teams.size() == 1 && teams.get(0).getCode().equals(teamCode)), "该团队负责不能重复负责多团队");
		// TeamItem teamItem = new TeamItem();
		// teamItem.setTeamCode(teamCode);
		// teamItem.setItemUserCode(leaderUserCode);
		// EntityUtil.initInsertEntity(teamItem);
		// this.teamItemService.insertTeamItem(teamItem);
	}

	@Transactional(transactionManager = "ticketTransactionManager")
	public void updateTeam(TeamUpdate teamUpdate) {
		initTeamItemWithLeader(teamUpdate.getCode(), teamUpdate.getLeaderUserCode());
		this.proxyDao.updateById(teamUpdate);
	}

	@Transactional(transactionManager = "ticketTransactionManager")
	public void deleteTeam(String id) {
		Team team = this.getTeamById(id);
		teamItemService.deleteTeamItemByTeamCode(team.getCode());
		this.proxyDao.deleteById(Team.class, id);
	}
}
